/**
 * @projectName:hxqbFront
 * @packageName:com.hx.qb.front.news.action
 * @className:NewsCenterAction.java
 * 
 * @createTime:2015年5月18日-下午4:50:22
 * 
 * 
 */
package com.yn.xr.front.news.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.csource.common.IniFileReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.yn.xr.common.constants.CommonDef;
import com.yn.xr.common.constants.CommonDef.SucceedOrFaultType;
import com.yn.xr.common.constants.NewsInfoDef;
import com.yn.xr.common.constants.NewsInfoDef.NewsType;
import com.yn.xr.common.exception.FileException;
import com.yn.xr.common.page.Page;
import com.yn.xr.common.properties.PropertyConfig;
import com.yn.xr.common.util.FastDFSUtils;
import com.yn.xr.common.util.Struts2Util;
import com.yn.xr.common.vo.FileVO;
import com.yn.xr.front.base.action.BaseAction;
import com.yn.xr.front.base.constants.RsCodeCon;
import com.yn.xr.front.base.constants.SystemConstants;
import com.yn.xr.front.news.service.NewsCenterService;
import com.yn.xr.news.mode.NewsInfo;

/**
 * @description:
 * @fileName:NewsCenterAction.java
 * @createTime:2015年5月18日 下午4:50:22
 * @author:HX1401125
 * @version 1.0.0
 * 
 */
@Scope("prototype")
@Controller("newsCenterAction")
public class NewsCenterAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	// 日志对象
	private static final Logger logger = LoggerFactory .getLogger(NewsCenterAction.class);

	@Resource
	private NewsCenterService newsCenterService; // 新闻
	
	@Resource
	private PropertyConfig accGateConfigurer;
	

	private Page<NewsInfo> page;

	private NewsInfo newsInfo;

	//新闻热度排行
    private List<NewsInfo> newsInfos;
	
  //操作状态  1：成功   0：失败  2:：添加  3：编辑
    private String operateStatus = "0";
    
    private File picFile;
    private String picFileFileName;
    private String picFileContentType;
    
    
    private String uploadFileName;
    private File upload;
    private String uploadContentType;
    
	/**
	 * @Description: 活动中心
	 * @author wangpinwen
	 * @date 2015年8月25日 下午9:44:07 
	 * @version V1.0.0
	 * @return
	 * @throws Exception
	 */
	public String newsCenterPage() throws Exception {
		try {
			request.setAttribute(SystemConstants.headFlag, CommonDef.FrontTabSort.NEWSCENTER.getValue());
			Object[] queryParams = null;
			String hql = "  status = ? and platformId = ? ";
			if( newsInfo == null ){
				hql += " and type = ?  order by createTime desc ";
				queryParams = new Object[]{SucceedOrFaultType.succeed.getValue(),SystemConstants.platformId,NewsType.HEANNEWS.getValue()};
			}else if( newsInfo.getType() != null ){
				hql += " and type = ?  order by createTime desc ";
				queryParams = new Object[]{SucceedOrFaultType.succeed.getValue(),SystemConstants.platformId,newsInfo.getType()};
			}else{
				hql += "  order by createTime desc ";
				queryParams = new Object[]{SucceedOrFaultType.succeed.getValue(),SystemConstants.platformId};
			}
			page = newsCenterService.newsCenterPage(hql, queryParams, pageNo, pageSize);
			ActionContext.getContext().put("page", page);

		} catch (Exception e) {
			logger.error("【----------查询新闻信息失败,出现异常:------------】" + e);
		}
		return super.toView("newsCenter");
	}
	
	 /**
	  * @Description: 新闻详情
	  * @author wangpinwen
	  * @date 2015年8月30日 下午3:57:39 
	  * @version V1.0.0
	  * @return
	  * @throws Exception
	  */
	public String queryNewsInfoDetail() throws Exception{
		try {
			request.setAttribute(SystemConstants.headFlag, CommonDef.FrontTabSort.NEWSCENTER.getValue());
			if (null != newsInfo && newsInfo.getNewsId() != null) {
				newsInfo = newsCenterService.getNewsById( newsInfo.getNewsId() );
				// 获取新闻热度排行
				newsInfos = newsCenterService.queryHotNewsInfo(Integer.valueOf(accGateConfigurer.getValueBykey(SystemConstants.HEATRANKLING_KEY)), SystemConstants.platformId, newsInfo.getType());
				// 获取相关新闻
				page = newsCenterService.queryOtherNewsInfoList(pageNo, Integer .parseInt(accGateConfigurer.getValueBykey(SystemConstants.RELATIVENEWSINFO_KEY)), newsInfo);
			}
		} catch (Exception e) {
			logger.error("【----------查询新闻详情失败,出现异常:------------】" + e);
		}
		return super.toView("news_detail");
	}
	
	
	/**
	 * 添加新闻
	 * @Description:添加新闻
	 * @author wangpinwen
	 * @date 2015年8月30日 下午3:57:29 
	 * @version V1.0.0
	 * @return
	 * @throws Exception
	 */
	public String toAddNewsInfo() throws Exception {
		this.setOperateStatus("2");// 2 代表添加
		this.setNewsInfo(initNewsInfo());
		//this.list = (getPlateformList());
		return super.toView("addNewsInfo");
	}


	// 初始化新闻对象
	public NewsInfo initNewsInfo() {
		NewsInfo newsInfo = new NewsInfo();
		newsInfo.setCanDiscuss(NewsInfoDef.CanDiscussStatus.CANDISCUSS.getValue());
        newsInfo.setStatus(SucceedOrFaultType.succeed.getValue());
        newsInfo.setRecommend(NewsInfoDef.RecommendStatus.NORECOMMEND.getValue());
		return newsInfo;
	}
    

	
	//添加新闻
	public String addNewsInfo() throws Exception {
		try {
			NewsInfo addNews = (NewsInfo) org.apache.commons.beanutils.BeanUtils.cloneBean(newsInfo);
			addNews.setPlatformId(SystemConstants.platformId);
			String fileName = this.saveNoticePic();
			addNews.setPicFileName(fileName);
			addNews.setCreateTime(new Date());
			addNews.setStatus(SucceedOrFaultType.succeed.getValue());
			
			
			
			newsCenterService.saveNewsInfo(addNews);
			operateStatus = "1";
		} catch (FileException e) {
			operateStatus = e.getErrorMsg();
			logger.error("【新闻添加失败】", e);
		} catch (Exception e) {
			logger.error("【新闻添加失败】", e);
		}
		return super.toView("addNewsInfo");
	}
	
	private String saveNoticePic() throws IOException, FileException {
		if (picFile != null) {
			if ((picFileContentType.equals("image/pjpeg") || picFileContentType.equals("image/jpeg")) && picFileFileName.substring(picFileFileName.length() - 4).toLowerCase().equals(".jpg")) {
				// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
			} else if (picFileContentType.equals("image/png") && picFileFileName.substring(picFileFileName.length() - 4) .toLowerCase().equals(".png")) {

			} else if (picFileContentType.equals("image/x-png") && picFileFileName.substring(picFileFileName.length() - 4) .toLowerCase().equals(".png")) {

			} else if (picFileContentType.equals("image/bmp") && picFileFileName.substring(picFileFileName.length() - 4) .toLowerCase().equals(".bmp")) {

			} else {
				throw new FileException(RsCodeCon.FILE_TYPE_INVALID, "文件格式不正确（必须为 .jpg/.jpeg/.png 文件）");
			}

			if (picFile.length() > 3000 * 1024) {
				throw new FileException(RsCodeCon.FILE_TYPE_INVALID, "文件大小不得大于3M");
			}

			// 防止图片名重复
			String fileName = java.util.UUID.randomUUID().toString() .replace("-", ""); // 采用UUID的方式随机命名
			fileName += picFileFileName;
			try {
				FileVO imgVo = makeFileVo(picFile, fileName);
				if (imgVo.isOK()) {
					logger.info("图片保存成功了");
					return imgVo.getGroupName() + "/" + imgVo.getNewFileName();
				}
			} catch (Exception e) {
				// e.printStackTrace();
			}
			// photoRmiService.saveNoticeTltPic(FileUtils.readFileToByteArray(picFile),
			// fileName);
		}
		return null;
	}
	 /**
     * @description:  上传图片至文件服务器
     * @param upload
     * @param name
     * @return
     * @throws Exception
     * @since V1.0.0
     * @author 陈权
     * @data 2015年6月2日
   */
	private FileVO makeFileVo(File upload, String name) throws Exception {
		FileVO fileInfo = null;
		try {
			if (upload != null) {
				String configRootPath = Struts2Util.class_path;
				fileInfo = FastDFSUtils.upload(upload, configRootPath, name, FastDFSUtils.getFileFormat(name));
			}
		} catch (Exception e) {
			LOG.error(this.toString() + ":" + e.getMessage());
			throw e;
		}
		return fileInfo;
	}
	
	/**
	 * @Description: 上传图片至服务器
	 * @author wangpinwen
	 * @date 2015年8月30日 下午5:50:44 
	 * @version V1.0.0
	 * @return
	 * @throws Exception
	 */
	public String uploadImg() throws Exception {
		String url = "";
		String reBackIMGname = "";
		// 对文件进行校验
		if (null != upload) {
			String callback = request.getParameter("CKEditorFuncNum");

			if ((uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg"))
					&& uploadFileName.substring(uploadFileName.length() - 4)
							.toLowerCase().equals(".jpg")) {
				// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
			} else if (uploadContentType.equals("image/png")
					&& uploadFileName.substring(uploadFileName.length() - 4)
							.toLowerCase().equals(".png")) {

			} else if (uploadContentType.equals("image/gif")
					&& uploadFileName.substring(uploadFileName.length() - 4)
							.toLowerCase().equals(".gif")) {

			} else if (uploadContentType.equals("image/bmp")
					&& uploadFileName.substring(uploadFileName.length() - 4)
							.toLowerCase().equals(".bmp")) {

			} else {
				response.setContentType("text/html;charset=utf-8");
				request.setCharacterEncoding("utf-8");
				super.outStr("<script type=\"text/javascript\"> alert('文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');</script>");
				return null;
			}

			if (upload.length() > 3000 * 1024) {
				response.setContentType("text/html;charset=utf-8");
				request.setCharacterEncoding("utf-8");
				super.outStr("<script type=\"text/javascript\"> alert('文件大小不得大于3M');</script>");
				return null;
			}
			// 防止图片名重复
			String fileName = java.util.UUID.randomUUID().toString()
					.replace("-", ""); // 采用UUID的方式随机命名
			uploadFileName.replaceAll("-", "");
			fileName += uploadFileName;
			FileVO imgVo = makeFileVo(upload, fileName);
			if (imgVo.isOK()) {
				logger.info("图片保存成功了");
				reBackIMGname = imgVo.getGroupName() + "/"+ imgVo.getNewFileName();
			}
			String configRootPath = Struts2Util.class_path;
			String classPath = configRootPath == null ? new File(
					FastDFSUtils.class.getResource("/").getFile())
					.getCanonicalPath() : configRootPath;
			String configFilePath = classPath + File.separator + "fdfs_client.conf";
			IniFileReader iniReader = new IniFileReader(configFilePath.replace(
					"%20", " "));
			url = iniReader.getStrValue("imgserver");
			// 设置返回“图像”选项卡
			super.outStr("<script type=\"text/javascript\">"
					+ "window.parent.CKEDITOR.tools.callFunction(" + callback
					+ ",'" + "" + url + "" + reBackIMGname + "','')"
					+ "</script>");
			return null;
		}
		return null;
	}
    
	public Page<NewsInfo> getPage() {
		return page;
	}

	public void setPage(Page<NewsInfo> page) {
		this.page = page;
	}

	public NewsInfo getNewsInfo() {
		return newsInfo;
	}

	public void setNewsInfo(NewsInfo newsInfo) {
		this.newsInfo = newsInfo;
	}

	public List<NewsInfo> getNewsInfos() {
		return newsInfos;
	}

	public void setNewsInfos(List<NewsInfo> newsInfos) {
		this.newsInfos = newsInfos;
	}

	public String getOperateStatus() {
		return operateStatus;
	}

	public void setOperateStatus(String operateStatus) {
		this.operateStatus = operateStatus;
	}

	public File getPicFile() {
		return picFile;
	}

	public void setPicFile(File picFile) {
		this.picFile = picFile;
	}

	public String getPicFileFileName() {
		return picFileFileName;
	}

	public void setPicFileFileName(String picFileFileName) {
		this.picFileFileName = picFileFileName;
	}

	public String getPicFileContentType() {
		return picFileContentType;
	}

	public void setPicFileContentType(String picFileContentType) {
		this.picFileContentType = picFileContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	
}
